package cn.hamster3.mc.plugin.ball.bukkit.listener;

import cn.hamster3.mc.plugin.ball.bukkit.util.BallBukkitUtils;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerLoginEvent;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerLogoutEvent;
import com.google.common.eventbus.Subscribe;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class UpdatePlayerInfoListener implements Listener {
    public static final UpdatePlayerInfoListener INSTANCE = new UpdatePlayerInfoListener();

    private final Map<UUID, String> PLAYER_PROXY_SERVER = new ConcurrentHashMap<>();

    private UpdatePlayerInfoListener() {
    }

    @Subscribe
    public void onBallPlayerLogin(BallPlayerLoginEvent event) {
        BallPlayerInfo info = event.getPlayerInfo();
        PLAYER_PROXY_SERVER.put(info.getUuid(), info.getProxyServer());
    }

    @EventHandler(ignoreCancelled = true)
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        BallPlayerInfo playerInfo = new BallPlayerInfo(
                player.getUniqueId(),
                player.getName(),
                BallAPI.getInstance().getLocalServerId(),
                PLAYER_PROXY_SERVER.getOrDefault(player.getUniqueId(), "unknown"),
                true
        );
        BallBukkitUtils.uploadPlayerInfo(playerInfo);
    }

    @Subscribe
    public void onBallPlayerLogout(BallPlayerLogoutEvent event) {
        BallPlayerInfo playerInfo = BallAPI.getInstance().getPlayerInfo(event.getPlayerInfo().getUuid());
        if (playerInfo == null) {
            return;
        }
        if (!BallAPI.getInstance().isLocalServer(playerInfo.getGameServer())) {
            return;
        }
        playerInfo.setOnline(false);
        BallBukkitUtils.uploadPlayerInfo(playerInfo);
    }
}
